<template>
  <div class="company-home">
    <!-- 顶部标题 -->
    <van-nav-bar :title="title" left-arrow @click-left="goBack" />
    
    <!-- 顶部企业信息 -->
    <div class="header">
      <div class="logo-container">
        <img :src="company.logo" alt="企业Logo" class="logo" @error="onImageError" />
      </div>
      <div class="info">
        <h2 class="company-name">{{ company.name }}</h2>
        <div v-if="company.status" class="status-badge" :class="statusClass">
          {{ company.status }}
        </div>
        <div class="rating">
          <span class="label">满意度</span>
          <van-rate
            v-model="company.rating"
            readonly
            size="16"
            color="#FFD700"
            void-color="#ddd"
            void-icon="star-o"
          />
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-card">
      <div class="stat-item">
        <div class="value">{{ stats.complaintCount }}</div>
        <div class="label">投诉量</div>
      </div>
      <div class="divider"></div>
      <div class="stat-item">
        <div class="value">{{ stats.repliedCount }}</div>
        <div class="label">已回复</div>
      </div>
      <div class="divider"></div>
      <div class="stat-item">
        <div class="value">{{ stats.resolvedCount }}</div>
        <div class="label">已完成</div>
      </div>
      <div class="divider"></div>
      <div class="stat-item">
        <div class="value">近30天</div>
        <div class="label">统计周期</div>
      </div>
    </div>

    <!-- 投诉列表（Tab 切换 + 分页加载） -->
    <div class="tabs-content">
      <van-tabs v-model:active="activeTab" class="custom-tabs">
        <van-tab :title="item.tname" v-for="item in titleData" :key="item.tid">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多数据啦～"
            @load="loadData"
          >
            <!-- 单个投诉项 -->
            <div v-for="(complain, index) in pageDate" :key="index" class="complain-item" @click="gotoComplaintDetail(complain.complaintId)">
              <!-- 头部区域 -->
              <div class="header">
                <img :src="getAvatar(complain.userId)" class="avatar" />
                <div class="user-info">
                  <div class="username">{{ getAnonName(complain.userId) }}</div>
                  <div class="date">{{ formatDate(complain.createTime) }} 于黑猫投诉平台发起</div>
                </div>
                <!-- 右上角状态标签 -->
                <div :class="['status-tag', `status-${complain.status}`]">
                  <van-icon class="tag-icon" :name="getStatusIcon(complain.status)"/>
                  {{ getStatusText(complain.status) }}
                </div>
              </div>

              <!-- 主体内容 -->
              <div class="content">
                <!-- 标题 -->
                <div class="title-row">
                  <span class="hot-label" v-if="titleData[activeTab]?.type === 'hot' && index < 3">热</span>
                  <span class="main-title">{{ complain.title }}</span>
                </div>

                <!-- 描述 -->
                <div class="description">{{ complain.description }}</div>

                <!-- 投诉对象和问题 -->
                <div class="details">
                  <div class="detail-row">
                    <span class="label">投诉对象</span>
                    <span class="value">{{ complain.merchantName }}</span>
                  </div>
                  <div class="detail-row">
                    <span class="label">投诉问题</span>
                    <van-tag round plain>{{ complain.subject }}</van-tag>
                  </div>
                </div>
              </div>
            </div>
            <!-- 空状态 -->
            <div v-if="pageDate.length === 0 && !loading" class="empty-state">
              <p>{{ titleData[activeTab]?.tname }}暂无数据</p>
            </div>
          </van-list>
        </van-tab>
        <van-divider />
      </van-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getFindMainComplaintsPageByCompanyId } from '@/api'
import { Icon as VanIcon } from 'vant'


const activeTab = ref(0);

const titleData = ref([
  { tid: 2, tname: "最新投诉", type: 'latest' },
  { tid: 3, tname: "已回复", type: 'replied' },
  { tid: 4, tname: "已完成", type: 'resolved' },
]); 

const title = "商家主页"

// 匿名列表
const anon = ref([
  "勇敢喵",
  "正义喵",
  "洞察喵",
  "机灵喵",
  "友爱喵"
])

// 头像列表
const avatar = ref([
  "/toux-cat1.png",
  "/toux-cat2.png",
  "/toux-cat3.png",
  "/toux-cat4.png",
])

const statusMap = {
  pending: '待分配',
  processing: '处理中',
  resolved: '已完成',
  replied: '已回复'
};

// 统一变量名：保持与使用处一致
const statusIcon = {
  pending: '/status-icon4.png',
  processing: '/status-icon2.png',
  resolved: '/status-icon1.png',
  replied: '/status-icon3.png'
}

// 每页大小（和后端一致）
const pageSize = 5;

// 每个 tab 的状态缓存
const tabStates = ref({
  latest: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  },
  replied: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  },
  resolved: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  }
});

// 当前激活 Tab 的状态（响应式引用）
const currentTabState = computed(() => {
  const type = titleData.value[activeTab.value]?.type;
  return type ? tabStates.value[type] : null;
});

// 页面显示的数据（响应式）
const pageDate = computed(() => {
  const type = titleData.value[activeTab.value]?.type;
  return type ? tabStates.value[type].list : [];
});

const loading = ref(false);
const finished = ref(false);

// 通用加载函数
const loadData = async () => {
  const currentType = titleData.value[activeTab.value]?.type;
  if (!currentType) return;

  const state = tabStates.value[currentType];
  if (state.loading || state.finished) return;

  // 更新状态
  state.loading = true;
  loading.value = true;

  try {
    const res = await getFindMainComplaintsPageByCompanyId({
      pageNum: state.currentPage,
      pageSize: pageSize,
      companyId: Number(props.id),
      status: currentType
    });

    const newData = res?.data?.pageInfo || res?.pageInfo || [];

    if (newData.length === 0) {
      state.finished = true;
      finished.value = true;
    } else {
      state.list.push(...newData);
      console.log("分页+1");
      
      state.currentPage++;
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    finished.value = false; // 错误时不标记完成，允许重试
  } finally {
    state.loading = false;
    loading.value = false;
  }
};

// 获取中文状态
const getStatusText = (statusKey) => {
  return statusMap[statusKey] || '未知状态';
};

// 获取状态图标（使用统一后的变量名）
const getStatusIcon = (statusKey) => {
  return statusIcon[statusKey] || '/status-icon4.png';
};

// 接收 props
const props = defineProps({
  id: {
    type: [String, Number],
    required: true
  }
})

const route = useRoute()
const router = useRouter()

// 图片加载失败时使用默认头像
const onImageError = (e) => {
    e.target.src = 'http://localhost:9977/upload/2025/10/17/company4.jpg'
}

// 企业 Logo 计算
const finalLogo = computed(() => {
  const logo = route.query.logo
  if (!logo) return 'http://localhost:9977/upload/2025/10/17/company4.jpg'
  if (logo.startsWith('http')) return logo
  return `http://localhost:9977${logo}`
})

// 企业基本信息
const company = ref({
  id: props.id,
  name: route.query.name || '未知企业',
  logo: finalLogo.value,
  rating: 3.5,
  status: '未匹配'
})

// 统计数据（可从后端获取）
const stats = ref({
  complaintCount: 0,
  repliedCount: 0,
  resolvedCount: 0
})

// 企业状态样式计算属性（补充缺失）
const statusClass = computed(() => {
  const status = company.value.status
  if (status.includes('已匹配')) return 'matched'
  if (status.includes('未匹配')) return 'unmatched'
  return ''
})

const goBack = () => {
  router.go(-1);
};

// 获取匿名昵称（修正引用变量名）
const getAnonName = (userId) => {
  return anon.value[userId % anon.value.length]
}

// 获取头像（修正引用变量名）
const getAvatar = (userId) => {
  return avatar.value[userId % avatar.value.length]
}

// 格式化时间
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toISOString().split('T')[0]
}

// 跳转详情页（统一函数名）
const gotoComplaintDetail = (complaintId) => {
  if (complaintId == null) return;
  router.push({
    name: 'complaintDetail',
    params: { cId: complaintId }
  });
};

// 监听 tab 切换，自动加载数据
watch(activeTab, (newIndex) => {
  const type = titleData.value[newIndex]?.type;
  if (!type) return;

  const state = tabStates.value[type];

  // 同步到顶层 loading/finished
  loading.value = state.loading;
  finished.value = state.finished;

  // 如果当前 Tab 还没加载过数据，则触发加载
  if (state.list.length === 0 && !state.loading && !state.finished) {
    loadData();
  }
}, { immediate: true });
</script>

<style scoped>
/* ===== 全局样式 ===== */
.company-home {
  padding: 0;
  margin: 0;
  background-color: #f8f8f8;
  min-height: 100vh;
}

:deep(.van-nav-bar) {
  --van-nav-bar-height: 50px;
  margin-bottom: 16px;
}

:deep(.van-nav-bar__title) {
  font-size: 16px !important; /* 调整为合适大小 */
  font-weight: bold !important;
  color: #333 !important;
}

/* ===== 顶部企业信息 ===== */
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 0;
}

.logo-container {
  margin-right: 16px;
}

.logo {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info {
  flex: 1;
}

.company-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.status-badge {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
  margin-bottom: 8px;
}

.status-badge.matched {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-badge.unmatched {
  background-color: #fff2e8;
  color: #fa8c16;
}

.rating {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.label {
  margin-right: 8px;
}

/* ===== 数据统计卡片 ===== */
.stats-card {
  display: flex;
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  flex: 1;
  text-align: center;
}

.value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.label {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.divider {
  width: 1px;
  height: 40px;
  background-color: #eee;
  margin: auto 0;
}

/* ===== 投诉列表 ===== */
.tabs-content {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
  margin-bottom: 20px;
}

.custom-tabs {
  background-color: #fff;
  z-index: 99;
}

.van-tabs__nav {
  border-bottom: 1px solid #eee;
}

.van-tabs__nav .van-tab--active {
  color: #333;
  font-weight: 500;
}

.van-tabs__nav .van-tab {
  padding: 12px 0;
  font-size: 14px;
}

.van-list {
  padding: 0;
}

/* ===== 投诉项样式 ===== */
.complain-item {
  padding: 16px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  cursor: pointer;
}

.complain-item:hover {
  background-color: #fafafa;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info {
  margin-left: 12px;
  flex: 1;
}

.username {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.date {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  border-radius: 4px;
  padding: 2px 8px;
  font-weight: 500;
}

.tag-icon {
  width: 12px;
  height: 12px;
}

.status-pending { color: #999; }
.status-processing { color: #ff9900; }
.status-replied { color: #03bcff; }
.status-resolved { color: #07c160; }

.content {
  margin-top: 8px;
}

.title-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.hot-label {
  background-color: #e83c3c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 6px;
}

.main-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  /* -webkit-line-clamp: 2; */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.details {
  margin-top: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.detail-row .label {
  font-size: 14px;
  color: #999;
  min-width: 70px;
}

.detail-row .value {
  font-size: 14px;
  color: #333;
  margin-left: 2px;
}

/* ===== 空状态 ===== */
.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}
</style>